import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

public class SQLHandler extends AbstractHandler implements IHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
//		Display display = Display.getCurrent();
//		Shell shell = new Shell(display);
//		MessageDialog.openInformation(shell, "PlungInClient", "gugugugugu");
		ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getSelection();
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		String transferData = null;
		if(selection instanceof ITextSelection) {
			ITextSelection textselect = (ITextSelection) selection;
			transferData = textselect.getText();
		}
		if(transferData==null||"".equals(transferData.trim())) {
			try {
				transferData = (String) toolkit.getSystemClipboard().getData(DataFlavor.stringFlavor);
			} catch (HeadlessException | UnsupportedFlavorException | IOException e) {
				e.printStackTrace();
			}
		}
		
		StringSelection stringSel = new StringSelection(parse(transferData));
		toolkit.getSystemClipboard().setContents(stringSel, null);
		return null;
	}
	

	private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
	private static SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//	private static String sql = "==>  Preparing: SELECT _baseInfo.*, _timesheet.DURATION FROM TEMP_CHECK_TIMESHEET_BASEINFO _baseInfo, TEMP_CHECK_TIMESHEET _timesheet WHERE _baseInfo.`ID` = _timesheet.CHECK_TIMESHEET_BASE_ID and _baseInfo.SHEET_DATE >= DATE_FORMAT(?, '%Y-%m-%d') and _baseInfo.SHEET_DATE <= DATE_FORMAT(?, '%Y-%m-%d') AND _baseInfo.COMPANY_ID =? AND _baseInfo.DEPT_ID =? GROUP BY EMPLOYEE_NAME, SHEET_DATE ORDER BY EMPLOYEE_NAME, SHEET_DATE LIMIT ?,? \n" + 
//			"==> Parameters: 2021-02-22 00:00:00(String), 2021-02-28 23:59:59(String), 65056(String), 65064(String), 10(Long), 10(Long)";
	public String parse(String sql) {
		String preSql = "==>  Preparing: ";
		String param = "==> Parameters: ";
		String[] split = sql.split("\n");
		String a = null;
		String b = null;
		for (String sp : split) {
			if(sp.contains(preSql)) {
				a = sp;
			}
			if(sp.contains(param)) {
				b = sp;
			}
		}
		if(a==null||"".equals(a.trim())) {
			return "sql语句不能为空：sql  ["+sql+"]";
		}
		a = sub(a,preSql);
		b = sub(b,param);
		String[] params = b.split(", ");
		List<String> paramList = parseParam(params);
		int length = paramList.size();
		for (int i = 0; i < length; i++) {
			a = a.replaceFirst("\\?", paramList.remove(0));
		}
		return a;
	}
	
	private static String sub(String source,String sub) {
		if(source.contains(sub)) {
			int indexOf = source.indexOf(sub);
			return source.replace(source.substring(0, indexOf+sub.length()), "");
		}
		return source;
	}

	private static List<String> parseParam(String[] params) {
		List<String> result = new ArrayList<>();
		Pattern pattern = Pattern.compile("(?<=\\()[^\\)]+");
		for (String param : params) {
			Matcher matcher = pattern.matcher(param);
			if (matcher.find()) {
				String type = matcher.group();
				String data = param.replace("(" + type + ")", "");
				switch (type) {
				case "Timestamp":
					try {
						result.add("'" + sf1.format(sf.parse(data)) + "'");
					} catch (ParseException e) {
						result.add("?");
						e.printStackTrace();
					}
					break;
				case "String":
					result.add("'" + data + "'");
					break;
				case "Long":
				case "Integer":
					result.add(data);
					break;
				default:
					result.add("?");
					break;
				}
			}
		}
		return result;
	}

}
